import 'package:flutter/material.dart';
import 'package:netflix_social/models/user.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:netflix_social/constants/app_constants.dart';

class AuthProvider with ChangeNotifier {
  User? _currentUser;
  bool _isLoading = false;
  String? _token;
  bool _isLoggedIn = false;

  User? get currentUser => _currentUser;
  bool get isLoading => _isLoading;
  String? get token => _token;
  bool get isLoggedIn => _isLoggedIn;

  // 在应用启动时检查登录状态
  Future<void> checkLoginStatus() async {
    _isLoading = true;
    notifyListeners();

    try {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString(AppConstants.tokenKey);
      final isLoggedIn = prefs.getBool(AppConstants.isLoggedInKey) ?? false;

      if (token != null && isLoggedIn) {
        _token = token;
        _isLoggedIn = true;
        // 在实际应用中，您可能会在此处从API获取用户数据
        // 现在我们只是使用模拟数据
        _currentUser = User(
          id: '1',
          username: '阿明',
          email: 'aming@example.com',
          avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
          bio: '热爱电影，尤其是科幻片',
          followersCount: 843,
          followingCount: 125,
          watchCount: 286,
          membershipType: '黄金会员',
          membershipExpiry: DateTime(2025, 12, 31),
          isVerified: true,
        );
      }
    } catch (e) {
      print('检查登录状态时出错: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 模拟登录过程
  Future<bool> login(String email, String password) async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会发送API请求进行身份验证
      // 这里我们只是模拟一个成功的登录
      await Future.delayed(const Duration(seconds: 1));

      // 模拟成功登录后的用户
      _currentUser = User(
        id: '1',
        username: '阿明',
        email: email,
        avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
        bio: '热爱电影，尤其是科幻片',
        followersCount: 843,
        followingCount: 125,
        watchCount: 286,
        membershipType: '黄金会员',
        membershipExpiry: DateTime(2025, 12, 31),
        isVerified: true,
      );

      _token = 'mock_token_${DateTime.now().millisecondsSinceEpoch}';
      _isLoggedIn = true;

      // 保存登录状态到本地存储
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(AppConstants.tokenKey, _token!);
      await prefs.setBool(AppConstants.isLoggedInKey, true);
      await prefs.setString(AppConstants.userIdKey, _currentUser!.id);
      await prefs.setString(AppConstants.usernameKey, _currentUser!.username);

      return true;
    } catch (e) {
      print('登录时出错: $e');
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 模拟注册过程
  Future<bool> register(String username, String email, String password) async {
    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会发送API请求进行注册
      // 这里我们只是模拟一个成功的注册过程
      await Future.delayed(const Duration(seconds: 1));

      // 注册成功后直接登录用户
      _currentUser = User(
        id: '1',
        username: username,
        email: email,
        avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
        bio: '',
        followersCount: 0,
        followingCount: 0,
        watchCount: 0,
        membershipType: '普通会员',
        membershipExpiry: DateTime.now().add(const Duration(days: 30)),
        isVerified: false,
      );

      _token = 'mock_token_${DateTime.now().millisecondsSinceEpoch}';
      _isLoggedIn = true;

      // 保存登录状态到本地存储
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(AppConstants.tokenKey, _token!);
      await prefs.setBool(AppConstants.isLoggedInKey, true);
      await prefs.setString(AppConstants.userIdKey, _currentUser!.id);
      await prefs.setString(AppConstants.usernameKey, _currentUser!.username);

      return true;
    } catch (e) {
      print('注册时出错: $e');
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 退出登录
  Future<void> logout() async {
    _isLoading = true;
    notifyListeners();

    try {
      // 清除用户数据和登录状态
      _currentUser = null;
      _token = null;
      _isLoggedIn = false;

      // 从本地存储中删除登录信息
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(AppConstants.tokenKey);
      await prefs.remove(AppConstants.isLoggedInKey);
      await prefs.remove(AppConstants.userIdKey);
      await prefs.remove(AppConstants.usernameKey);
    } catch (e) {
      print('退出登录时出错: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 更新用户资料
  Future<bool> updateProfile({
    String? username,
    String? email,
    String? avatar,
    String? bio,
  }) async {
    if (_currentUser == null) return false;

    _isLoading = true;
    notifyListeners();

    try {
      // 在实际应用中，您会发送API请求更新资料
      // 这里我们只是模拟一个成功的更新
      await Future.delayed(const Duration(seconds: 1));

      _currentUser = _currentUser!.copyWith(
        username: username,
        email: email,
        avatar: avatar,
        bio: bio,
      );

      return true;
    } catch (e) {
      print('更新个人资料时出错: $e');
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
